package com.sunjob.loginserver.config;

import com.fasterxml.jackson.databind.ser.std.StringSerializer;
import com.sunjob.common.constant.MROConstant;
import com.sunjob.common.domain.loginServer.SysMenu;
import com.sunjob.common.domain.loginServer.SysRole;
import com.sunjob.loginserver.service.MenuService;
import com.sunjob.loginserver.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Wangzurong
 * @create 2022-07-28 11:00
 */
@Component
public class RoleAuthInitConfig implements ApplicationRunner {
    @Autowired
    RoleService roleService;
    @Autowired
    MenuService menuService;
    @Autowired
    RedisConnectionFactory redisConnectionFactory;
    @Override
    public void run(ApplicationArguments args) throws Exception {
        List<SysRole> roles = roleService.queryAllRole();
        List<SysMenu> menuList = menuService.queryAllMenu();
        StringRedisSerializer stringSerializer = new StringRedisSerializer();
        GenericJackson2JsonRedisSerializer valueSerializer = new GenericJackson2JsonRedisSerializer();
        // 角色和权限缓存到redis
        try (RedisConnection connection = redisConnectionFactory.getConnection();){
            Map<byte[],byte[]> map= new HashMap<>();
            roles.stream().forEach(e->{
                map.put(stringSerializer.serialize(e.getRoleId()+""),valueSerializer.serialize(e));
                List<String> menus = menuService.queryMenuByRole(e.getRoleId() + "");
                connection.hashCommands().hSet(stringSerializer.serialize(MROConstant.ROLE_MENUS),stringSerializer.serialize(e.getRoleId()+""),valueSerializer.serialize(menus));
            });
            Map<byte[],byte[]> map1 = new HashMap<>();
            menuList.stream().forEach(e->{
                map1.put(stringSerializer.serialize(e.getMenuId()+""),valueSerializer.serialize(e));
            });
            connection.hashCommands().hMSet(stringSerializer.serialize(MROConstant.ROLES),map);
            connection.hashCommands().hMSet(stringSerializer.serialize(MROConstant.MENUS),map1);
        }


    }
}
